import { login, logout, getInfo, GQL } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import md5 from 'js-md5';



const  state = {
  token: getToken(),
  name: '',
  avatar: '',
  other: {},
  roles: []
}

const mutations = {
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      const pwd = md5(password)
      const query = {
        "operationName": "allSlSystemAdmins",
        "query": "query allSlSystemAdmins($filter: SlSystemAdminFilter) { allSlSystemAdmins(filter:$filter) { nodes { account headPic id pwd status roles realName isDel } } }",
        "variables": { "filter": { "account": { "equalTo":  username},"pwd":{"equalTo":pwd} } }
      }
      GQL(query).then(response => {
          const data = response.data.allSlSystemAdmins.nodes[0]
          console.log('res---',response)
          commit('SET_TOKEN', data.id)
          commit('SET_AVATAR', data.head_pic)
          commit('SET_NAME', data.real_name)
          setToken(data.id)
          resolve()
      }).catch(error => {
        reject(error)
      })
     
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { real_name, head_pic,roles } = data
        commit('SET_NAME', real_name)
        commit('SET_AVATAR', head_pic)
        commit('SET_ROLES', roles)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken() // must remove  token  first
        resetRouter()
        resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken() // must remove  token  first
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

